import { login, getMenuList } from "@/api/user";
import { Message } from 'iview'

export default {
    state: {
        user: "", // 用户信息
        access: "", // 用户权限
        unreadCount: 3, // 用户未读消息
        hasGetInfo: false, // 获取用户信息是否成功
        loading: false //加载
    },
    actions: {
        /* 登录 */
        handleLogin({ commit, state }, { userName, password, code }) {
            state.loading = true
            /* 去除字符串两边的空白 */
            userName = userName.trim();
            return new Promise((resolve, reject) => {
                login({ userName, password, code })
                    .then(res => {
                        state.loading = false
                        if (res.state === "success") {
                            commit("setUser", res.data);
                            resolve(res.data.uid);
                        } else {
                            Message.error(res.message);
                        }
                    })
                    .catch(err => {
                        reject(err);
                    });
            });
        },
        /* 获取导航信息 */
        getMenuList({ state }) {
            return new Promise((resolve, reject) => {
                try {
                    getMenuList(state.user.roleid)
                        .then(res => {
                            const menuList = res.data
                            const user = { ...state.user, menuList }
                            sessionStorage.setItem('user', JSON.stringify(user))
                            resolve(res)
                        })
                        .catch(err => {
                            reject(err);
                        });
                } catch (error) {
                    reject(error);
                }
            });
        }
    },
    mutations: {
        /* 设置用户id */
        setUser(state, data) {
            state.user = data;
        },
        /* 有没有用户信息 */
        setHasGetInfo(state, status) {
            state.hasGetInfo = status;
        },
    }
};
